from PySide6.QtGui import QImage, QPixmap, qRgb
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QColorDialog, QMessageBox
from ui.ui_bg import Ui_MainWindow
from threading import Thread
from PIL import Image

from utils.bg_utils import run_bg_replace


class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.cwd = "./"
        self.color_picker = QColorDialog
        self.input_image_path = None
        self.input_image = None
        self.output_image_path = "./output/temp.jpg"
        self.output_image = None
        self.bind()

    def bind(self):
        self.ui.uploadButton.clicked.connect(self.slot_upload_file)
        self.ui.bgColorButton.clicked.connect(self.slot_color_picker)
        self.ui.saveButton.clicked.connect(self.slot_save_file)

    def slot_upload_file(self):
        # 选取路径 # 设置文件扩展名过滤,用双分号间隔
        # file_name, filetype = QFileDialog.getOpenFileName(self, "选取文件", self.cwd, "All Files (*);;Text Files (*.txt)")
        file_name, filetype = QFileDialog.getOpenFileName(self, "选取文件", self.cwd, 'Image files (*.jpg *.png *.jpeg)')

        if file_name == "":
            # print("\n取消选择")
            return

        # print("\n你选择的文件为:")
        # print(file_name)
        # print("文件筛选器类型: ", filetype)

        # 获取所选图片路径
        self.input_image_path = file_name
        self.input_image = Image.open(file_name)
        # print(type(self.input_image))
        self.output_image = self.input_image

        image = QPixmap(self.input_image_path)
        new_image = self.image_resize(image)
        self.ui.original_image.setPixmap(new_image)
        self.ui.processed_image.setPixmap(new_image)

    # 对输入图片进行缩放
    def image_resize(self, image):
        # 获取原图片的宽与高
        width = image.width()
        height = image.height()

        # 获取比例
        if width / self.ui.original_image.width() >= height / self.ui.original_image.height():
            ratio = width / self.ui.original_image.width()
        else:
            ratio = height / self.ui.original_image.height()

        # 获取新图片的宽与高
        new_width = width / ratio
        new_height = height / ratio

        # 调整原图片大小
        new_image = image.scaled(new_width, new_height)  # 调整图片尺寸
        return new_image

    # 打开颜色对话框
    def slot_color_picker(self):
        # 如果尚未上传任何图片 则报错
        if self.input_image_path is None:
            self.show_no_image_error()
            return

        # self.color_picker.setCustomColor(0, qRgb(199, 199, 199))
        color = self.color_picker.getColor()

        # 当出发cancel时函数直接返回
        if not color.isValid():
            print("颜色无效！")
            return

        # 获取背景颜色
        bg_color = (color.red(), color.green(), color.blue())
        # 完成背景颜色的替换 并获取结果
        self.output_image = run_bg_replace(self.input_image, bg_color)
        # run_bg_replace(self.input_image_path, bg_color)

        # 根据输出的图片地址生成QPixmap
        image = QPixmap(self.output_image_path)
        # 重置展示大小
        new_image = self.image_resize(image)
        # 在预览图片控件上进行替换
        self.ui.processed_image.setPixmap(new_image)

    # 展示错误界面
    def show_no_image_error(self):
        QMessageBox.critical(self, "错误", "请先上传图片！")

    # 展示图片保存成功页面
    def show_save_image_success(self):
        QMessageBox.information(self, "结果", "保存成功！")

    def slot_save_file(self):
        # 如果output_image为空
        if self.output_image is None:
            self.show_no_image_error()
            return

        # 前面是地址，后面是文件类型,得到输入地址的文件名和地址txt(*.txt*.xls);;image(*.png)不同类别
        filepath, filetype = QFileDialog.getSaveFileName(self, "图片保存", "/", 'image(*.jpg)')
        # print(filepath)
        self.output_image.save(filepath)

        # 弹出保存成功消息框
        self.show_save_image_success()


if __name__ == '__main__':
    app = QApplication()
    window = MainWindow()
    window.show()
    app.exec()
